#!/usr/bin/php -q
<?php
exit;
//THIS SCRIPT NEEDS TO BE RUN IN COMBINATION WITH SECURITY THROUGH A FIREWALL AND WHERE IT CANNOT BE ACCESSED BY UNTRUSTED USERS, IT DOES NOT OFFER ANY BUILT IN SECURITY AND IF RUN AS ROOT CAN PROVIDE ROOT ACCESS TO ARBITRARY COMMANDS

// On startup, create listening socket and listen on local loopback interface
$mysocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($mysocket, '127.0.0.1', 23451) or die('[FATAL] Line '.__LINE__.': '.socket_strerror(socket_last_error())."\n");
socket_listen($mysocket, 1) or die('[FATAL] Line '.__LINE__.': '.socket_strerror(socket_last_error())."\n");

echo "Waiting for a connection...\n";

$run = true;
while($run) {
        $connection = socket_accept($mysocket);
        echo "Accepted a new connection...\n";
        process($connection);
}
socket_shutdown($mysocket);

function process($socket)
{
        global $logDir;
        socket_send($socket,"HELLO\n",4096,0);
        $cmd = trim(socket_read($socket, 4096, PHP_NORMAL_READ));

        if ($cmd == 'EXIT') {
                echo "Closing \n";
                $GLOBALS['run'] = false;
        }
        else {
                echo "Running: $cmd ";

                passthru ($cmd);
		exec("killall PagePrint-bin");

		echo "Complete\n";
                socket_send($socket,"GOODBYE\n\n",4096,0);
        }

	echo "Closing Socket\n";
        socket_close($socket);
	echo "Socked Closed\n";
}
?>

